/*
package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.ActivityKind;
import com.ruoyi.common.enums.BundleId;
import com.ruoyi.common.utils.AppUserAgentGenerator;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.ProxyGetTask;
import com.ruoyi.system.domain.ProxyRequest;
import com.ruoyi.system.domain.ProxySendTask;
import com.ruoyi.system.domain.RequestEntity;
import com.ruoyi.system.domain.vo.getTask.GetTaskResponse;
import com.ruoyi.system.domain.vo.getTask.Param;
import com.ruoyi.system.domain.vo.sendTask.SendTaskResponse;
import com.ruoyi.system.mapper.ProxyGetTaskMapper;
import com.ruoyi.system.mapper.ProxyRequestMapper;
import com.ruoyi.system.mapper.ProxySendTaskMapper;
import com.ruoyi.system.service.IProxyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

*/
/**
 * 菜单 业务层
 *
 * @author ruoyi
 *//*

@Service
public class IProxyServiceImpl2 implements IProxyService {

//    private static final String API_URL_TEMPLATE = "http://api.ipipgo.com/ip?cty=RU&c=%d&pt=1&ft=json&rep=1&key=877a8eae&ts=%d";

    private static final String BASEURL = "https://app.adjust.com/1c2u9v2x";

    private static final Logger logger = LoggerFactory.getLogger(IProxyService.class);
    public static final String SUCCESS_CACHE_LIST = "SUCCESS_CACHE_LIST";

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ProxyGetTaskMapper proxyGetTaskMapper;

    @Autowired
    private ProxyRequestMapper proxyRequestMapper;

    @Autowired
    private ProxySendTaskMapper proxySendTaskMapper;


    @Override
    public void proxyToSDK(RequestEntity request, String count, String bundle_id) throws IOException {

        for (int i = 0; i < Integer.parseInt(count); i++) {
            try {
                String response = sendRequestWithProxy(bundle_id);
                logger.info("发送请求结束，响应内容为:{} ", response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static String toQueryParams(Object entity) {
        StringBuilder queryParams = new StringBuilder("?");
        Field[] fields = entity.getClass().getDeclaredFields();

        try {
            for (Field field : fields) {
                field.setAccessible(true);
                String name = field.getName();
                if ("port".equals(name)) {
                    continue;
                }
                Object value = field.get(entity);

                if (value != null) {
                    if (queryParams.length() > 1) {
                        queryParams.append("&");
                    }
                    queryParams.append(name)
                            .append("=")
                            .append(URLEncoder.encode(value.toString(), StandardCharsets.UTF_8.toString()));
                }
            }
        } catch (IllegalAccessException | UnsupportedEncodingException e) {
            e.printStackTrace();  // Log or handle the error properly
        }
        return queryParams.toString();
    }


//    public static List<String> fetchProxies(int c, int ts) {
////        int c = 10; // 请求代理数量
////        int ts = 30; // 请求间隔时间（分钟）
//        String urlString = String.format(API_URL_TEMPLATE, c, ts);
//        List<String> proxies = new ArrayList<>();
//        RequestConfig config = RequestConfig.custom()
//                .setConnectTimeout(10000)
//                .setSocketTimeout(10000)
//                .setConnectionRequestTimeout(3000)
//                .build();
//        CloseableHttpClient httpClient = HttpClients.custom()
//                .setDefaultRequestConfig(config)
//                .build();
//        HttpGet request = new HttpGet(urlString);
//        HttpResponse response = null;
//        try {
//            response = httpClient.execute(request);
//
//        int responseCode = response.getStatusLine().getStatusCode();
//        if (responseCode == 200) {
//            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
//            String inputLine;
//            StringBuilder responseContent = new StringBuilder();
//            while ((inputLine = in.readLine()) != null) {
//                responseContent.append(inputLine);
//            }
//            in.close();
//
//            JSONObject jsonResponse = JSON.parseObject(responseContent.toString());
//            JSONArray proxyArray = jsonResponse.getJSONArray("data");
//            for (int i = 0; i < proxyArray.size(); i++) {
//                JSONObject proxyObject = proxyArray.getJSONObject(i);
//                String ip = proxyObject.getString("ip");
//                int port = proxyObject.getIntValue("port");
//                proxies.add(ip + ":" + port);
//            }
//        }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return proxies;
//    }

    public static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(characters.charAt(random.nextInt(characters.length())));
        }
        return sb.toString();
    }

    public static String generateRandomStringToken(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/+";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(characters.charAt(random.nextInt(characters.length())));
        }
        return sb.toString();
    }

    public String sendRequestWithProxy(String bundle_id) throws Exception {
        RequestEntity entity = new RequestEntity();
        String clickId = DateUtils.dateTimeNow() + "_" + generateRandomString(8);
        BundleId bundleIdByCode = BundleId.getBundleIdByCode(bundle_id);
        if (BundleId.APPQUAKE == bundleIdByCode) {
            entity.setClickid(clickId);
            entity.setEvent_callback_7lguti("https://www.szytop.com/testproxy?clickid=" + clickId);
        } else if (BundleId.MAANA == bundleIdByCode) {
            entity.setClick_id(clickId);
            entity.setEvent_callback_46feya("https://www.szytop.com/testproxy?clickid=" + clickId);
        } else if (BundleId.YTAXI == bundleIdByCode) {
            entity.setClickid(clickId);
            entity.setEvent_callback_2ce2yw("https://www.szytop.com/testproxy?clickid=" + clickId);
//            entity.setClick_id(clickId);
//            entity.setCard_product("cake_credit_card");
//            entity.setAdj_t("1e4ok1fu");
//            entity.setAdj_campaign(bundleIdByCode.getAppName());
//            entity.setAdj_adgroup("Pru_kentP");
//            entity.setAdj_creative("Pru_kentP");
//            entity.setAdj_install_callback("http://www.szytop.com:8080/testproxy?clickid=" + clickId);
//            entity.setAdj_rejected_install_callback("http://www.szytop.com:8080/testproxy?clickid=" + clickId);
        }
        entity.setIdfa(Objects.toString(UUID.randomUUID()).toUpperCase());
        entity.setIdfv(Objects.toString(UUID.randomUUID()).toUpperCase());
        entity.setUser_agent(AppUserAgentGenerator.getRandomIOSUserAgent());

        entity.setRejected_install_callback("https://www.szytop.com/testproxy?clickid=" + clickId);
        entity.setInstall_callback("https://www.szytop.com/testproxy?clickid=" + clickId);
        assert bundleIdByCode != null;
        entity.setCampaign(bundleIdByCode.getAppName());
        entity.setCreative("subid_creative_" + clickId);
//        entity.setAdgroup(bundleIdByCode.getAppName());
        HttpHost proxy = new HttpHost("proxy.ipipgo.com", 31212, "http");
        entity.setIp_address(proxy.getHostName());
        String url = bundleIdByCode.getUrl() + toQueryParams(entity);
        //代理开始

        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(proxy), new org.apache.http.auth.UsernamePasswordCredentials("customer-d9cd86-country-RU", "65f87cd8"));

        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(3000)
                .build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(config)
                .build();
        //代理结束---------------

        HttpGet request = new HttpGet(url);
        request.setConfig(config);
        HttpResponse response = httpClient.execute(request);
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode == 200) {
            //24消失自动过期了
//            redisCache.setCacheObject(clickId, JSON.toJSON(entity), 1440, TimeUnit.MINUTES);
            saveRequest(entity, clickId);
//            List<String> arraylist = new ArrayList<>();
//            arraylist.add(clickId);
//            redisCache.setCacheList(SUCCESS_CACHE_LIST, arraylist);
            return getString(response);
        } else {
            throw new Exception("请求失败，响应代码: " + responseCode);
        }
    }

    private void saveRequest(RequestEntity entity, String clickId) {
        Date date = new Date();
        ProxyRequest record = new ProxyRequest();
        record.setAppName(entity.getCampaign());
        if(StringUtils.isEmpty(entity.getCampaign())){
            record.setAppName(entity.getAdj_campaign());
        }

        record.setRequestId(clickId);
        record.setCreateTime(date);
        record.setUpdateTime(date);
        record.setRequestValue(JSON.toJSONString(entity));
        record.setIsSuccess("0");
        proxyRequestMapper.insert(record);
    }


    @Override
    public void sendRequestWithProxyReal(SendTaskResponse obj) {
        //clickId 再次重新生成
        Param param = obj.getParam();
        HashMap<String, String> header = obj.getHeader();
        String activityKind = obj.getActivityKind();
        handleRequest(activityKind, param, header, obj.getRequest_id());
    }


    public void handleRequest(String activityKind, Param param, Map<String, String> header, String requestId) {
        HttpHost proxy = new HttpHost("proxy.ipipgo.com", 31212, "http");
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(proxy), new org.apache.http.auth.UsernamePasswordCredentials("customer-d9cd86-country-RU", "65f87cd8"));
        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(3000)
                .build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(config)
                .build();
        try {
            ProxySendTask insert = new ProxySendTask();
            CloseableHttpResponse closeableHttpResponse = null;
            if (ActivityKind.SESSION.getCode().equals(activityKind)) {
                HttpPost request = new HttpPost(ActivityKind.SESSION.getUrl());
                setHeaders(request, header);
                request.setEntity(new UrlEncodedFormEntity(convertParams(param), StandardCharsets.UTF_8));
                closeableHttpResponse = executeRequest(httpClient, request, activityKind);
            } else if (ActivityKind.SDK_CLICK.getCode().equals(activityKind)) {
                HttpPost request = new HttpPost(ActivityKind.SDK_CLICK.getUrl());
                setHeaders(request, header);
                request.setEntity(new UrlEncodedFormEntity(convertParams(param), StandardCharsets.UTF_8));
                closeableHttpResponse = executeRequest(httpClient, request, activityKind);
            } else if (ActivityKind.ATTRIBUTION.getCode().equals(activityKind)) {
                HttpGet request = new HttpGet(ActivityKind.ATTRIBUTION.getUrl() + toQueryParams(param));
                setHeaders(request, header);
                closeableHttpResponse = executeRequest(httpClient, request, activityKind);
            } else if (ActivityKind.EVENT.getCode().equals(activityKind)) {
                HttpPost request = new HttpPost(ActivityKind.EVENT.getUrl());
                setHeaders(request, header);
                request.setEntity(new UrlEncodedFormEntity(convertParams(param), StandardCharsets.UTF_8));
                closeableHttpResponse = executeRequest(httpClient, request, activityKind);
            } else if (ActivityKind.SDK_INFO.getCode().equals(activityKind)) {
                HttpPost request = new HttpPost(ActivityKind.EVENT.getUrl());
                setHeaders(request, header);
                request.setEntity(new UrlEncodedFormEntity(convertParams(param), StandardCharsets.UTF_8));
                closeableHttpResponse = executeRequest(httpClient, request, activityKind);
            }
            inserSend(activityKind, param, insert, closeableHttpResponse, requestId);
        } catch (Exception e) {
            logger.error("请求失败: ", e);
        }
    }

    private void inserSend(String activityKind, Param param, ProxySendTask insert, CloseableHttpResponse closeableHttpResponse, String requestId) {
        insert.setActivityKind(activityKind);
        insert.setAppName(BundleId.getAppNameByCode(param.getBundle_id()));
        insert.setBundleId(param.getBundle_id());
        Date date = new Date();
        insert.setCreateTime(date);
        insert.setUpdateTime(date);
        insert.setRequestParam(JSON.toJSONString(param));
        insert.setResponseParam(JSON.toJSONString(closeableHttpResponse));
        insert.setRequestId(requestId);
        proxySendTaskMapper.insert(insert);
    }

    private List<BasicNameValuePair> convertParams(Param param) throws IllegalAccessException {
        List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
        Field[] fields = param.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            String value = (String) field.get(param);
            if (value != null) {
                nameValuePairs.add(new BasicNameValuePair(name, value));
            }
        }
        return nameValuePairs;
    }

    private void setHeaders(HttpRequestBase request, Map<String, String> header) {
        request.setHeader("User-Agent", header.get("User-Agent"));
        request.setHeader("Client-Sdk", header.get("Client-Sdk"));
        request.setHeader("Accept", header.get("Accept"));
        request.setHeader("Accept-Language", header.get("Accept-Language"));
        request.setHeader("Authorization", header.get("Authorization"));
        if (request instanceof HttpPost) {
            request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        }
    }

    private CloseableHttpResponse executeRequest(CloseableHttpClient httpClient, HttpUriRequest request, String activityKind) {
        try {
            printStartLog(request);
            CloseableHttpResponse response = httpClient.execute(request);
            logger.info("模拟{}请求抓包请求的结果为:{}", activityKind, getString(response));
            return response;
        } catch (Exception e) {
            logger.error("请求失败: ", e);
        }
        return null;
    }

    private void printStartLog(HttpUriRequest request) {
        try {
            String method = request.getMethod();
            String path = request.getURI().getPath();
            String url = request.getURI().toString();
            String header = toHeaderString(request);
            String params = method.equalsIgnoreCase("GET") ? getQueryParams(request) : getPostParams(request);

            logger.info("模拟抓包的请求参数为 Method: {}, Path: {}, URL: {}, Headers: {}, Params: {}", method, path, url, header, params);
        } catch (Exception e) {
            logger.error("failed to print request info");
        }
    }

    private String getQueryParams(HttpUriRequest request) {
        try {
            String query = request.getURI().getQuery();
            return query != null ? query : "{}";  // 如果有查询参数则返回，没有则返回"{}"
        } catch (Exception e) {
            return "{}";  // 在异常情况下返回空对象表示没有参数
        }
    }

    private String getPostParams(HttpUriRequest request) {
        try {
            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                if (entity != null) {
                    try (InputStream inputStream = entity.getContent();
                         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                        // 使用 BufferedReader 和 Stream API 来收集所有行并拼接成字符串
                        String body = reader.lines().collect(Collectors.joining(System.lineSeparator()));
                        return body.isEmpty() ? "{}" : body;
                    }
                }
            }
        } catch (Exception e) {
            // 处理异常并返回空对象表示没有参数
            return "{}";
        }
        return "{}";  // 如果不是 POST 请求或者请求体为空，则返回 "{}"
    }

    private String toHeaderString(HttpUriRequest request) {
        StringBuilder stringBuilder = new StringBuilder();
        // HttpUriRequest接口不直接提供获取所有header的功能，通常需要从具体的实现类中获取
        // 这里提供一个处理思路，具体实现可能需要根据HttpClient的版本调整
        for (Header header : request.getAllHeaders()) {
            stringBuilder.append(header.getName()).append("=").append(header.getValue()).append(" ");
        }
        return stringBuilder.toString();
    }


    private String getString(HttpResponse response) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String inputLine;
        StringBuilder responseContent = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            responseContent.append(inputLine);
        }
        in.close();
        return responseContent.toString();
    }


    @Override
    public AjaxResult getAjaxResult(String bundle_id) {
        AjaxResult ajax = AjaxResult.success();
        //取出所有成功的数量
        String appName = BundleId.getAppNameByCode(bundle_id);
        if (StringUtils.isEmpty(appName)) {
            ajax.put("result", null);
            return ajax;
        }
//        int allProxyRequest = proxyRequestMapper.countAllProxyRequest(appName);
//        int successProxyRequest = proxyRequestMapper.countSucessProxyRequest(appName);
//        int numberToSelect = (int) Math.ceil(allProxyRequest * 0.1);
////        //成功数量>占比数量
//        if (successProxyRequest > numberToSelect || (successProxyRequest == 0 && allProxyRequest == 0)) {
//            ajax.put("result", null);
//            return ajax;
//        }
//
//        List<ProxyRequest> proxyRequests = proxyRequestMapper.selectAllProxyRequest(appName);
//        if (CollectionUtils.isEmpty(proxyRequests)) {
//            ajax.put("result", null);
//            return ajax;
//        }
//        ProxyRequest proxyRequest = proxyRequests.get(0);
//        RequestEntity entity = JSON.parseObject(proxyRequest.getRequestValue(), RequestEntity.class);
        RequestEntity entity =new RequestEntity();
        entity.setIdfv(UUID.randomUUID().toString().toUpperCase());
        entity.setIdfa(UUID.randomUUID().toString().toUpperCase());

        GetTaskResponse resp = new GetTaskResponse();
        HashMap<String, String> head = new HashMap<>();
        head.put("Accept", "/");
        head.put("Accept-Language", "zh-cn");
        head.put("Authorization", "");
        head.put("User-Agent","APPMetricaDemo/1 CFNetwork/1197 Darwin/20.0.0");
        head.put("Client-Sdk", "ios5.0.0");

//        String userAgent = entity.getUser_agent();
//
//        Pattern pattern = Pattern.compile("\\(iOS (\\d+\\.\\d+); (\\w+,\\d+)\\)", Pattern.CASE_INSENSITIVE);
//        Matcher matcher = pattern.matcher(userAgent);

//        Pattern pattern = Pattern.compile("\\(iOS (\\d+\\.\\d+); (\\w+,\\d+)\\)");
//        Matcher matcher = pattern.matcher(userAgent);
        String primary_dedupe_token = UUID.randomUUID().toString().toLowerCase();


//        Param para0 = getParamSdkClick(entity, bundle_id, primary_dedupe_token);
        Param para1 = getParamSession(entity, bundle_id, primary_dedupe_token);
        Param para2 = getParamEvent1(entity, bundle_id,primary_dedupe_token);
        Param para3 = getParamAttribution(entity, bundle_id, primary_dedupe_token);

//        para0.setDevice_name(device); // 设备
//        para0.setOs_version(iosVersion); // 手机设备版本

//        Param para3 = getParamEvent1(entity, bundle_id,primary_dedupe_token);
//        head.put("User-Agent", "Maana/24071818 CFNetwork/1390 Darwin/22.0.0");
//        if (matcher.find()) {
//            String iosVersion = matcher.group(1);
//            IOSVersionInfo byVersion = IOSVersionInfo.getByVersion(iosVersion);
//            assert byVersion != null;
//            String.format("Maana/24071818 CFNetwork/%s %s",
//                    byVersion.getCfNetworkVersion(),
//                    byVersion.getDarwinVersion());
//            head.put("User-Agent", String.format("Maana/24071818 CFNetwork/%s %s",
//                    byVersion.getCfNetworkVersion(),
//                    byVersion.getDarwinVersion()));
//
//            String device = matcher.group(2);
//            para0.setDevice_name(device); // 设备
//            para0.setOs_version(iosVersion); // 手机设备版本
//            para1.setDevice_name(device); // 设备
//            para1.setOs_version(iosVersion); // 手机设备版本
//            para2.setDevice_name(device); // 设备
//            para2.setOs_version(iosVersion); // 手机设备版本
//            para3.setDevice_name(device); // 设备
//            para3.setOs_version(iosVersion); // 手机设备版本
////            para4.setDevice_name(device); // 设备
////            para4.setOs_version(iosVersion); // 手机设备版本
//        }
        resp.setHeader(head);
        resp.setHTTPMethod("POST");


        List<Param> paras = new ArrayList<>();
//        paras.add(para0);
        paras.add(para1);
        paras.add(para2);
        paras.add(para3);
//        paras.add(para4);

        resp.setParam(paras);
        String jsonString = JSON.toJSONString(resp);
        logger.info("/aj/ios/getTask的返回参数为:{}", jsonString);
        ajax.put("result", resp);
//        updateAndInsert(bundle_id, proxyRequest, jsonString);
        return ajax;
    }

    private void updateAndInsert(String bundle_id, ProxyRequest proxyRequest, String jsonString) {
        proxyRequestMapper.updateProxyRequest(proxyRequest);
        ProxyGetTask rqs = new ProxyGetTask();
        Date date = new Date();
        rqs.setAppName(proxyRequest.getAppName());
        rqs.setCreateTime(date);
        rqs.setRequestId(proxyRequest.getRequestId());
        rqs.setBundleId(bundle_id);
        rqs.setIsSendTask(0);
        rqs.setResponse(jsonString);
        rqs.setUpdateTime(date);
        proxyGetTaskMapper.insert(rqs);
    }


    private static Param getParamSdkClick(RequestEntity entity, String bundle_id, String primary_dedupe_token) {
        Param para = getParam(entity, bundle_id, "sdk_click", primary_dedupe_token);
//        para.setError_code("100");

        para.setAtt_status("0"); // 固定 按照抓包参数来
        para.setTime_spent(Objects.toString(ThreadLocalRandom.current().nextInt(1, 60)));
        para.setSubsession_count("1");
        para.setSession_count("1"); // 固定  按照抓包参数来
        para.setSource("apple_ads");
        para.setLast_interval("0");
        para.setSession_length("0");
        para.setAttribution_token(generateRandomStringToken(98)+"AAAVADAAAAnwAAAICA4qblbTQTOWcaAZz52C8th7zWOjvSWq39HTHAejDltOF/LMTkbMvZXpuQNEgii9/qJlHEeggcr1accB9N8/NSQ48kFTwIF9YAzXOl4b6ZkAqP91JIz10vIjuVBV1dXEgez30FoT50qE2OVoTuJZRspALPwWJIFnaWVBOvyp0IWQAAABWpLSDNQJmebxd4Souk3VkEz1gDkC8AAACfAZe7K5ITwxUKh642s47wvpbDFUeqAAAAhgAAWSVsPk5X8sKdv0N/C3i8dma0yd3ReZ9ms+aWNN/rvSLfKqpWy22hTAIrT9j9kQY5uz8yFUSRZBdXNXRYO0km+LUx9k3ggpsOG6uKPazoSkw2buJQaXpSMsxgxGIkB/H0KsaT9LeR5a8BfqcRsjC8IHkYjBCkNfWNPdaAxoYEbWSFoFl8AAAAAAAAAAAAAAABBEcRAAA=");

//        para.setForeground("1");
//        para.setSend_in_background_enabled("0");
//        para.setOffline_mode_enabled("0");


        return para;
    }

    private static Param getParamSession(RequestEntity entity, String bundle_id, String primary_dedupe_token) {
        Param para = getParam(entity, bundle_id, "session", primary_dedupe_token);
        para.setSession_count("1"); // 固定  按照抓包参数来
        para.setAtt_status("0"); // 固定 按照抓包参数来
        para.setForeground("1");
        para.setRetry_count("0");
        para.setSend_in_background_enabled("0");
        para.setEnqueue_size("0");
        para.setOffline_mode_enabled("0");

        return para;
    }

    private static Param getParamAttribution(RequestEntity entity, String bundle_id, String primary_dedupe_token) {
        Param para = getParam(entity, bundle_id, "attribution", primary_dedupe_token);
        para.setSend_in_background_enabled("0");
        para.setInitiated_by("sdk");
        para.setAtt_status("0"); // 固定 按照抓包参数来
        return para;
    }

    private static Param getParamEvent1(RequestEntity entity, String bundle_id, String primary_dedupe_token) {
        Param para = getParam(entity, bundle_id, "event", primary_dedupe_token);
//        para.setCallback_params("{\"user_id\":\"z61c019e5ae94658b940663c195ae7f1\"}");
        para.setForeground("1");
        para.setRetry_count("0");
        para.setEvent_count("1");
        para.setSession_count("1"); // 固定  按照抓包参数来
        para.setSend_in_background_enabled("0");
        para.setSession_length("7");
        para.setEnqueue_size("1");
        para.setTime_spent(Objects.toString(ThreadLocalRandom.current().nextInt(1, 60)));
        para.setSubsession_count("1");
        para.setOffline_mode_enabled("0");
        para.setAtt_status("0"); // 固定 按照抓包参数来
        para.setEvent_token("icotnm");

        return para;
    }

    private static Param getParamSdkInfo(RequestEntity entity, String bundle_id, String primary_dedupe_token) {
        Param para = getParam(entity, bundle_id, "sdk_info", primary_dedupe_token);
        para.setSource("push");
        para.setForeground("1");
        para.setPush_token("4597C9E729451145E92CFC48E3B96C0052E6BEDE4D029F4DD3EBE21312AD25FB");
        para.setLast_interval("0");
        para.setSession_count("3"); // 固定  按照抓包参数来
        para.setSession_length("0");
        para.setEnqueue_size("2");
        para.setTime_spent(Objects.toString(ThreadLocalRandom.current().nextInt(1, 60)));
        para.setOffline_mode_enabled("0");
        para.setAtt_status("1"); // 固定 按照抓包参数来
        para.setWait_total("1.98");
        para.setRetry_count("0");// 固定 按照抓包参数来
        para.setPartner_params("");
        para.setSubsession_count("1");
        return para;
    }


    private static Param getParam(RequestEntity entity, String bundle_id, String activityKind, String primary_dedupe_token) {
        Param para = new Param();

        OffsetDateTime utcNow = OffsetDateTime.now(ZoneOffset.UTC);
        OffsetDateTime Installed_at_time = utcNow.plusMinutes(-ThreadLocalRandom.current().nextInt(5, 10));
        OffsetDateTime skadn_registered_time = Installed_at_time.plusMinutes(ThreadLocalRandom.current().nextInt(1, 2));
        OffsetDateTime start_at_time = utcNow.plusMinutes(-ThreadLocalRandom.current().nextInt(2000, 10000));

        OffsetDateTime created_at_time = skadn_registered_time.plusSeconds(ThreadLocalRandom.current().nextInt(5, 10));
        OffsetDateTime sent_at_time = created_at_time.plusNanos((long) ThreadLocalRandom.current().nextInt(5, 15) * 1000 * 1000);

        String Installed_at = getFormattedDateTime(Installed_at_time);
        String Skadn_registered_at = getFormattedDateTime(skadn_registered_time);
        String Started_at = getFormattedDateTime(start_at_time);
        String Created_at = getFormattedDateTime(created_at_time);
        String Sent_at = getFormattedDateTime(sent_at_time);
        //20个公共参数
        para.setDevice_name("iPhone10,1");
        para.setOs_version("14.1");

        para.setBundle_id(bundle_id); // 固定  按照抓包参数来
        para.setPrimary_dedupe_token(primary_dedupe_token); // 32位 自定义生成 保持唯一
        para.setApp_version("1"); // app版本 固定 按照抓包参数来
        para.setApp_version_short("1.0"); // 固定  按照抓包参数来
        para.setInstalled_at(Installed_at); // app安装时间
        para.setNeeds_response_details("1"); // 固定  按照抓包参数来
        para.setAttribution_deeplink("1"); // 固定  按照抓包参数来
        para.setSkadn_registered_at(Skadn_registered_at); // 启动app 注册sdk时间
        para.setOs_name("ios");
        para.setEvent_buffering_enabled("0"); // 固定
        para.setEnvironment("production"); // 固定  按照抓包参数来
        para.setApp_token("vtizz86ky6m8"); // 固定  按照抓包参数来
        para.setStarted_at(Started_at); // 创建请求时的时间
        para.setCreated_at(Created_at);
        para.setDevice_type("iPhone"); // 手机类型 固定
        para.setSent_at(Sent_at);
        para.setIdfv(entity.getIdfv()); // 32位 自定义生成 保持唯一
        para.setIdfa(entity.getIdfa());

        //这三个冗余
        para.setSdkVersion("ios5.0.0");
        para.setActivityKind(activityKind); // sdk类型  按照抓包参数来
        String reqId = DateUtils.dateTimeNow() + "_" + generateRandomString(8);
        para.setRequest_id(reqId); // 暂定clickId

        return para;
    }


    private static String getFormattedDateTime(OffsetDateTime formattedDateTime1) {
        // 获取当前时间的UTC时间
        OffsetDateTime utcPlusFiveHours = formattedDateTime1.withOffsetSameInstant(ZoneOffset.of("+08:00"));

        // 定义一个DateTimeFormatter来格式化日期时间字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
        String formattedDateTimeStr = utcPlusFiveHours.format(formatter);

        // 手动添加时区偏移量
        String offset = "Z+0800";
        return formattedDateTimeStr + offset;
    }

}
*/
